<script setup lang="tsx">
import { h, ref } from 'vue';
import { NButton, NImage, NPopconfirm, NTag } from 'naive-ui';
import { useAuth } from '@/hooks/business/auth';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import type { File } from '@/service/api';
import { deleteFile, fetchGetFileList } from '@/service/api';
import { $t } from '@/locales';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { fileSizeFormatter } from '@/utils/common';
import { useBoolean } from '~/packages/hooks/src';
import FileSearch from './modules/file-search.vue';
import FileOperateModel from './modules/file-operate-model.vue';
import FileViewerModel from './modules/file-viewer-model.vue';

const appStore = useAppStore();
const { hasAuth } = useAuth();

const wrapperRef = ref<HTMLElement | null>(null);

// 文件预览地址
const filePreviewUrl = ref('');
const previewFileTitle = ref('');

const { bool: fileViewerVisible, setTrue: openFileViewerModel } = useBoolean();

const {
  columns,
  columnChecks,
  data,
  loading,
  mobilePagination,
  getData,
  getDataByPage,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetFileList,
  showTotal: true,
  apiParams: {
    current: 1,
    size: 10,
    path: null,
    type: null,
    createTime: null
  },
  columns: () => [
    {
      key: 'name',
      title: $t('page.base.file.list.name'),
      align: 'center',
      width: 400,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'url',
      title: $t('page.base.file.list.url'),
      align: 'center',
      width: 400,
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'type',
      title: $t('page.base.file.list.type'),
      align: 'center',
      width: 150,
      render: row => <NTag>{row.type}</NTag>
    },
    {
      key: 'content',
      title: $t('page.base.file.list.content'),
      align: 'center',
      width: 200,
      render: row => {
        if (row.mineType.includes('image')) {
          return h(NImage, {
            width: 30,
            height: 30,
            src: row.url
          });
        } else if (
          row.type.includes('docx') ||
          row.type.includes('pdf') ||
          row.type.includes('xlsx') ||
          row.type.includes('pptx') ||
          row.type.includes('md') ||
          row.type.includes('csv') ||
          row.type.includes('txt')
        ) {
          return h(
            NButton,
            {
              dashed: true,
              type: 'primary',
              size: 'small',
              onClick: () => handlePreview(row)
            },
            {
              icon: () => h(SvgIcon, { icon: 'ep:view' })
            }
          );
        }
        return h(
          NButton,
          {
            dashed: true,
            type: 'primary',
            size: 'small',
            onClick: () => handleDownload(row)
          },
          {
            icon: () => h(SvgIcon, { icon: 'ep:download' })
          }
        );
      }
    },
    {
      key: 'size',
      title: $t('page.base.file.list.size'),
      align: 'center',
      width: 150,
      render: row => <div>{fileSizeFormatter(row.size)}</div>
    },
    {
      key: 'createTime',
      title: $t('page.base.file.list.createTime'),
      align: 'center',
      width: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      width: 120,
      render: row => (
        <div class="flex-center gap-8px">
          <div v-show={hasAuth('system:file_config:delete')}>
            <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
              {{
                default: () => $t('common.confirmDelete'),
                trigger: () => (
                  <NButton type="error" ghost size="small">
                    {{
                      default: () => $t('common.delete'),
                      icon: () => h(SvgIcon, { icon: 'ep:delete' })
                    }}
                  </NButton>
                )
              }}
            </NPopconfirm>
          </div>
        </div>
      )
    }
  ]
});

const { modelVisible, handleAdd, onDeleted, checkedRowKeys } = useTableOperate(data, getData);

/**
 * 删除文件
 *
 * @param id
 */
async function handleDelete(id: number) {
  // request
  const { error } = await deleteFile(id.toString());

  await onDeleted(error);
}

/**
 * 预览文件
 *
 * @param row
 */
function handlePreview(row: File) {
  filePreviewUrl.value = row.url;
  previewFileTitle.value = row.name;
  openFileViewerModel();
}

/**
 * 下载文件
 *
 * @param row
 */
function handleDownload(row: File) {
  // 创建一个隐藏的 a 标签
  const link = document.createElement('a');
  link.href = row.url;
  link.download = row.name; // 设置下载的文件名
  link.style.display = 'none';
  document.body.appendChild(link);

  // 触发点击事件
  link.click();

  // 清理
  document.body.removeChild(link);
}
</script>

<template>
  <div ref="wrapperRef" class="flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <FileSearch
      v-if="hasAuth('system:file:query')"
      v-model:model="searchParams"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />

    <NCard
      :title="$t('page.base.file.list.title')"
      :bordered="false"
      size="small"
      class="sm:flex-1-hidden card-wrapper"
    >
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          create-auth="system:file:create"
          delete-auth="system:file:delete"
          delete-show="false"
          :create-text="$t('page.base.file.list.uoloadFile')"
          @add="handleAdd"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="1688"
        :loading="loading"
        :row-key="row => row.id"
        remote
        :pagination="mobilePagination"
        class="sm:h-full"
      />

      <FileOperateModel v-model:visible="modelVisible" @submitted="getDataByPage" />

      <FileViewerModel
        v-model:visible="fileViewerVisible"
        :file-preview-url="filePreviewUrl"
        :preview-file-title="previewFileTitle"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
